package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.constant.HintConstant;
import org.example.demo.constant.MessageConstant;
import org.example.demo.entity.InformationHint;
import org.example.demo.entity.MeetingLog;
import org.example.demo.service.InformationHintService;
import org.example.demo.service.MeetingLogService;
import org.example.demo.service.UserMeetingService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 会议日志控制器
 */
@RestController
@RequestMapping("meetingLog")
public class MeetingLogController {

    @Resource
    private MeetingLogService meetingLogService;

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private UserMeetingService userMeetingService;


    @Autowired
    InformationHintService informationHintService;

    /**
     * 分页查询会议日志
     * 
     * @param meetingLog 查询条件
     * @param pageNum    页码
     * @param pageSize   每页大小
     * @return 查询结果
     */
    @PostMapping("page")
    public AjaxResult page(@RequestBody MeetingLog meetingLog,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<MeetingLog> page = meetingLogService.selectPage(meetingLog, pageNum, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("page", page);
        result.put("total", page.getTotal());

        return AjaxResult.success(result);
    }

    /**
     * 根据ID查询会议日志
     * 
     * @param id 会议日志ID
     * @return 查询结果
     */
    @GetMapping("{id}")
    public AjaxResult getById(@PathVariable Long id) {
        MeetingLog meetingLog = meetingLogService.getById(id);

        if (meetingLog != null) {
            return AjaxResult.success(meetingLog);
        } else {
            return AjaxResult.error("会议日志不存在");
        }
    }

    /**
     * 新增会议日志
     * 
     * @param meetingLog 会议日志信息
     * @return 操作结果
     */
    @Transactional
    @PostMapping
    public AjaxResult add(@RequestBody MeetingLog meetingLog) {
        meetingLog.setCreateTime(LocalDateTime.now());
        meetingLog.setUpdateTime(LocalDateTime.now());

        if (meetingLogService.save(meetingLog)) {
            // 把会议插入给这些人
            List<Long> meetingPeople = meetingLog.getMeetingPeople();
            Long meetingLogId = meetingLog.getId();

            userMeetingService.saveBatch(meetingLogId, meetingPeople);

            // 把会议插入给某个人的信息提醒
            for (Long userId : meetingPeople) {
                InformationHint informationHint = InformationHint.builder()
                        .userId(userId)
                        .title(HintConstant.MEETING_HINT)
                        .content(meetingLog.getMeetingTheme())
                        .time(meetingLog.getMeetingDate())
                        .build();

                informationHintService.save(informationHint);
            }

            return AjaxResult.success();
        } else {
            return AjaxResult.error(MessageConstant.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 修改会议日志
     * 
     * @param meetingLog 会议日志信息
     * @return 操作结果
     */
    @Transactional
    @PutMapping
    public AjaxResult update(@RequestBody MeetingLog meetingLog) {
        meetingLog.setUpdateTime(LocalDateTime.now());


        // 先删除
        List<Long> userIds = userMeetingService.getUserIdsByMeetingId(meetingLog.getId());
        for (Long userId : userIds) {
            userMeetingService.remove(meetingLog.getId(), userId);

        }

        if (meetingLogService.updateById(meetingLog)) {
            // 再增加
            List<Long> meetingPeople = meetingLog.getMeetingPeople();
            userMeetingService.saveBatch(meetingLog.getId(), meetingPeople);
            return AjaxResult.success();
        } else {
            return AjaxResult.error(MessageConstant.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 删除会议日志
     * 
     * @param id 会议日志ID
     * @return 操作结果
     */
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable Long id) {
        if (meetingLogService.removeById(id)) {

            // 删除用户会议关系的记录
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("meeting_id", id);
            userMeetingService.remove(wrapper);

            return AjaxResult.success();
        } else {
            return AjaxResult.error(MessageConstant.INTERNAL_SERVER_ERROR);
        }
    }
}